#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <unordered_map>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
// 假设Terminal.hpp不存在，若存在可保留，否则删除
// #include "Terminal.hpp"
typedef std::function<std::string(const std::string&)> fun_t;

class UdpServer
{
public:
    UdpServer(const uint16_t &port = 8888, const std::string &ip = "0.0.0.0")
        : port_(port), ip_(ip), sockfd_(0), isrunning_(false)
    {
    }

    void Init()
    {
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            perror("socket creat error");
            exit(-1);
        }
        std::cerr << "socket creat success\n";

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        // 修正：IP用inet_pton转换（支持IPv4标准格式，避免inet_addr的兼容性问题）
        if (inet_pton(AF_INET, ip_.c_str(), &local.sin_addr) <= 0)
        {
            perror("invalid ip");
            close(sockfd_);
            exit(-1);
        }

        int n = bind(sockfd_, (const struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            perror("bind error");
            close(sockfd_);
            exit(-2);
        }
        std::cerr << "bind success (ip:" << ip_ << ", port:" << port_ << ")\n";
    }

    // 修正1：
    std::string GetClientKey(const std::string &clientip, uint16_t clientport)
    {
        return clientip + ":" + std::to_string(clientport);
    }

    void CheckUser(const struct sockaddr_in &client, const std::string clientip, uint16_t clientport)
    {
        std::string key = GetClientKey(clientip, clientport);
        auto iter = online_user_.find(key);
        if (iter == online_user_.end())
        {
            online_user_.insert({key, client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }

    void Broadcast(const std::string &info, const std::string clientip, uint16_t clientport)
    {
        // 修正2：
        std::string info_with_null = info;
        info_with_null += '\0';

        for (const auto &user : online_user_)
        {
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]# ";
            message += info_with_null;

            socklen_t len = sizeof(user.second);
            // 发送广播消息，增加错误处理
            ssize_t send_len = sendto(sockfd_, message.c_str(), message.size(), 0, 
                                     (struct sockaddr*)(&user.second), len);
            if (send_len < 0)
            {
                perror("broadcast sendto error");
                continue;
            }
        }
    }

    void Run()
    {
        isrunning_ = true;
        char inbuffer[1024];
        while (isrunning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            memset(inbuffer, 0, sizeof(inbuffer)); // 初始化缓冲区，避免残留数据

            // 接收消息，
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0, 
                                (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                perror("recv error");
                continue;
            }
           
            inbuffer[n] = '\0';

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client, clientip, clientport);

            std::string info = inbuffer;
            std::cout << "Receive from [" << clientip << ":" << clientport << "]: " << info << std::endl;
            Broadcast(info, clientip, clientport);
        }
    }

    ~UdpServer()
    {
        if (sockfd_ > 0)
        {
            close(sockfd_);
        }
    }

private:
    int sockfd_;
    std::string ip_;
    uint16_t port_;
    bool isrunning_;
    // 修正4：用“IP:端口”作为键，存储每个客户端的唯一标识
    std::unordered_map<std::string, struct sockaddr_in> online_user_;
};